package nd.android.am;

import nd.android.am.Adapter.Account;
import nd.android.am.Adapter.Config;
import nd.android.am.Adapter.User;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class AccountList extends ListActivity {

	private static final String TAG = "AccountList";

    // Menu item ids
    public static final int MENU_ITEM_DELETE = Menu.FIRST;
    public static final int MENU_ITEM_INSERT = Menu.FIRST + 1;
    public static final int MENU_ITEM_UPDATE = Menu.FIRST + 2;
    public static final int MENU_ITEM_FILTER = Menu.FIRST + 3;
    public static final int MENU_ITEM_EXIT = Menu.FIRST + 4;
    public static final int MENU_ITEM_USER = Menu.FIRST + 5;
    public static final int MENU_ITEM_SETTLE = Menu.FIRST + 6;

    private long selectedId = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
		getIntent().setData(Account.CONTENT_URI);
		getListView().setOnCreateContextMenuListener(this);

		Cursor cursor = managedQuery(User.CONTENT_URI, new String[] { User._ID, User.NAME }, null, null,
				User.DEFAULT_SORT_ORDER);
		Adapter.cacheUsers(cursor);
//		cursor.close();
		cursor = managedQuery(Config.CONTENT_URI, new String[] { Config.NAME, Config.VALUE }, null, null,
				User.DEFAULT_SORT_ORDER);
		Adapter.cacheConfigs(cursor);
//		cursor.close();
		cursor = managedQuery(getIntent().getData(), Account.PROJECTION, null, null, Account.DEFAULT_SORT_ORDER);

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.account_item, cursor, 
				new String[] {Account.OCCUR_DATE, Account.PURPOSE, Account.AMOUNT },
				new int[] { R.id.date, R.id.purpose, R.id.amount });
		setListAdapter(adapter);
//		cursor.close();
	}

    //menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

		menu.add(0, MENU_ITEM_INSERT, 0, R.string.menu_insert)
				.setShortcut('3', 'a').setIcon(android.R.drawable.ic_menu_add);
		menu.add(0, MENU_ITEM_FILTER, 0, R.string.menu_filter)
				.setShortcut('4', 'f').setIcon(android.R.drawable.ic_menu_rotate);
		menu.add(0, MENU_ITEM_USER, 0, R.string.menu_peaple)
				.setShortcut('5', 'p').setIcon(android.R.drawable.ic_menu_camera);
		menu.add(0, MENU_ITEM_SETTLE, 0, R.string.menu_settle)
				.setShortcut('6', 's').setIcon(android.R.drawable.ic_menu_manage);
		menu.add(0, MENU_ITEM_EXIT, 0, R.string.menu_exit)
				.setShortcut('7', 'e').setIcon(android.R.drawable.ic_menu_close_clear_cancel);
        
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

//		long selectedItemId = getSelectedItemId();
//		boolean selected = selectedItemId > 0;
//		menu.findItem(MENU_ITEM_UPDATE).setEnabled(selected);
//		menu.findItem(MENU_ITEM_DELETE).setEnabled(selected);
		
		return true;
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ITEM_INSERT:
            startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
            return true;
        case MENU_ITEM_EXIT:
        	finish();
        	return true;
        case MENU_ITEM_FILTER:
        	return true;
        case MENU_ITEM_USER:
//            startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
        	return true;
        case MENU_ITEM_SETTLE:
        	 Intent i = new Intent(this, CalculateService.class);
        	 startService(i);
        	return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //context menu
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
//        AdapterView.AdapterContextMenuInfo info;
//        try {
//             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
//        } catch (ClassCastException e) {
//            Log.e(TAG, "bad menuInfo", e);
//            return;
//        }

//		menu.setHeaderTitle(title);
        menu.add(0, MENU_ITEM_UPDATE, 0, R.string.menu_update);
        menu.add(0, MENU_ITEM_DELETE, 1, R.string.menu_delete);
//      cursor.close();
    }
        
    @Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		} catch (ClassCastException e) {
			Log.e(TAG, "bad menuInfo", e);
			return false;
		}

		switch (item.getItemId()) {
		case MENU_ITEM_UPDATE: {
			Uri accountUri = ContentUris.withAppendedId(getIntent().getData(), info.id);
	        startActivity(new Intent(Intent.ACTION_EDIT, accountUri));
			break;
		}
		case MENU_ITEM_DELETE: {
			selectedId = info.id;
            showDialog(DIALOG_YES_NO_MESSAGE);
			break;
		}
		default: return false;
		}
		return true;
	}

    //dialog
    private static final int DIALOG_YES_NO_MESSAGE = 1;
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_YES_NO_MESSAGE:
            return new AlertDialog.Builder(this)
                .setTitle(R.string.confirm_title).setMessage(R.string.confirm_delete_message)
                .setPositiveButton(R.string.confirm_OK, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
            			Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), selectedId);
            			getContentResolver().delete(noteUri, null, null);
                    }
                })
                .setNegativeButton(R.string.confirm_Cancel, null)
                .create();
        }
        return null;
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
        startActivity(new Intent(Intent.ACTION_EDIT, uri));
    }
    
    
}
